<template>
  <div class="h-full">
    <n-space vertical>
      <n-card class="shadow-sm rounded-4px">
        <n-form class="w-full" size="small" inline>
          <n-form-item label="日期:" label-placement="left">
            <n-date-picker
              v-model:value="range"
              type="datetimerange"
              clearable
              :default-time="['00:00:00', '00:00:00']"
            />
          </n-form-item>
          <n-form-item label="车间:" label-placement="left" style="width: 200px">
            <n-select
              v-model:value="selectedAreas"
              clearable
              multiple
              label-field="areaname"
              value-field="areaname"
              :options="areas"
            />
          </n-form-item>

          <n-form-item label="" label-placement="left">
            <n-button type="primary" :on-click="getFpyData">
              <template #icon><icon-mdi-map-search-outline /></template>
              查询
            </n-button>
          </n-form-item>
        </n-form>
      </n-card>
    </n-space>
    <n-card class="rounded-4px shadow-sm">
      <vxe-grid v-bind="fpyOptions"></vxe-grid>
    </n-card>
    <n-modal v-model:show="showModal">
      <n-card style="width: 1200px" :bordered="false" size="huge" role="dialog" aria-modal="true">
        <vxe-grid v-bind="lotGridOptions"></vxe-grid>
      </n-card>
    </n-modal>
  </div>
</template>

<script setup lang="tsx">
import { onMounted, reactive, ref } from 'vue';
import dayjs from 'dayjs';
import type { LineSeriesOption } from 'echarts/charts';
import type { VxeGridProps } from 'vxe-table';
import type { ECOption } from '@/composables/echarts';
import { fetchAreaList, fetchFpyData, fetchFpyLotList } from '@/service/api';

const range = ref<[number, number]>([dayjs().startOf('month').valueOf(), Date.now()]);

const areas = ref<Factory.Area[]>([]);
const selectedAreas = ref([]);

const modelTypes = ref([]);
const selectedModelType = ref('');

const showModal = ref(false);

const myOption = ref<ECOption>({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  legend: {
    data: []
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: [],
  yAxis: [],
  series: []
});

const buildChartSelect = (data: Array<QualityReport.FpyData>) => {
  const chartModels: string[] = [];
  modelTypes.value = [];
  data.forEach(element => {
    if (!chartModels.includes(element.modeltype)) {
      chartModels.push(element.modeltype);
      modelTypes.value.push({ label: element.modeltype, value: element.modeltype });
    }
  });
  if (modelTypes.value.length > 0) {
    selectedModelType.value = modelTypes.value[0].value;
  }
};

const buildChart = (data: Array<QualityReport.FpyData>) => {
  const legendData: string[] = [];
  const xAxisData: string[] = [];

  data.forEach(element => {
    if (!legendData.includes(element.area)) {
      legendData.push(element.area);
    }
    if (!xAxisData.includes(element.datetime)) {
      xAxisData.push(element.datetime);
    }
  });
  const seriesList: LineSeriesOption[] = [];
  for (let i = 0; i < legendData.length; i += 1) {
    const seriesItem: LineSeriesOption = {
      name: legendData[i],
      type: 'line',
      smooth: 0.6,
      data: [0]
    };
    const seriesData = [];
    for (let j = 0; j < xAxisData.length; j += 1) {
      const target = data.filter(item => {
        return (
          item.datetime === xAxisData[j] && item.area === legendData[i] && item.modeltype === selectedModelType.value
        );
      });
      if (target.length > 0) {
        seriesData.push(target[0].fpy);
      } else {
        seriesData.push(0);
      }
    }
    seriesItem.data = seriesData as number[];
    seriesList.push(seriesItem);
  }
  myOption.value = {
    tooltip: {},
    legend: {
      data: legendData
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      data: xAxisData
    },
    yAxis: {},
    series: seriesList as any
  };
};

const lotGridOptions = reactive<VxeGridProps>({
  border: true,
  size: 'mini',
  showFooter: true,
  align: null,
  columnConfig: {
    resizable: true
  },
  columns: [
    {
      field: 'EVENTTIME',
      title: '时间'
    },
    {
      field: 'OLDAREANAME',
      title: '车间',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'PROCESSOPERATIONNAME',
      title: '工序',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'PRODUCTSPECNAME',
      title: '产品料号',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'LOTNAME',
      title: '工单号',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'EVENTUSER',
      title: '操作员'
    },
    {
      field: 'YIELD',
      title: '良率'
    }
  ],
  toolbarConfig: {
    buttons: [],
    export: true,
    print: true,
    // zoom: true,
    custom: true
  },
  data: [],
  mergeCells: [],
  exportConfig: {
    remote: false,
    types: ['xlsx'],
    modes: ['current', 'selected', 'all']
  }
});

// eslint-disable-next-line max-params
const getFpyLotList = async (dateTime: string, area: string, modelType: string, operation: string) => {
  const result = await fetchFpyLotList(dateTime, area, modelType, operation, '', '');
  if (result.data) {
    lotGridOptions.data = result.data;
  }
};

const showDetailEvent = (row: any, opreation: string) => {
  showModal.value = true;
  getFpyLotList(row.datetime, row.area, row.modeltype, opreation);
};

const fpyOptions = reactive<VxeGridProps>({
  border: true,
  // height: 300,
  size: 'mini',
  showFooter: true,
  align: null,
  columnConfig: {
    resizable: true
  },
  columns: [
    {
      field: 'datetime',
      title: '日期',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'area',
      title: '车间',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'modeltype',
      title: '型号',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      title: '工序名称/工序良率',
      children: [
        {
          field: 'dumoyield',
          title: '镀膜良率',
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.dumoyield !== '0' && row.dumoyield !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R03')}>
                    {row.dumoyield}
                  </span>
                ) : (
                  row.dumoyield
                )
              ];
            }
          }
        },
        {
          field: 'dianjiaoyield',
          title: '点胶良率',
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.dianjiaoyield !== '0' && row.dianjiaoyield !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R04')}>
                    {row.dianjiaoyield}
                  </span>
                ) : (
                  row.dianjiaoyield
                )
              ];
            }
          }
        },
        {
          field: 'weitiaoyield',
          title: '微调良率',
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.weitiaoyield !== '0' && row.weitiaoyield !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R07')}>
                    {row.weitiaoyield}
                  </span>
                ) : (
                  row.weitiaoyield
                )
              ];
            }
          }
        },
        {
          field: 'fenghanyield',
          title: '封焊良率',
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.fenghanyield !== '0' && row.fenghanyield !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R08')}>
                    {row.fenghanyield}
                  </span>
                ) : (
                  row.fenghanyield
                )
              ];
            }
          }
        },
        {
          field: 'ceshiyield',
          title: '测试良率',
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.ceshiyield !== '0' && row.ceshiyield !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R14')}>
                    {row.ceshiyield}
                  </span>
                ) : (
                  row.ceshiyield
                )
              ];
            }
          }
        }
      ]
    },
    {
      field: 'fpy',
      title: '直通率'
    }
  ],
  toolbarConfig: {
    buttons: [],
    export: true,
    print: true,
    // zoom: true,
    custom: true
  },
  data: [],
  mergeCells: [],
  exportConfig: {
    remote: false,
    types: ['xlsx'],
    modes: ['current', 'selected', 'all']
  }
});

const getFpyData = async () => {
  const result = await fetchFpyData(
    dayjs(range.value[0]).format('YYYYMMDDHHmmss'),
    dayjs(range.value[1]).format('YYYYMMDDHHmmss'),
    selectedAreas.value.join(','),
    '',
    ''
  );
  if (result.data) {
    const rawData: Array<QualityReport.FpyData> = result.data;
    rawData.forEach(element => {
      const shangpianYield = Number(element.shangpianyield) === 0 ? 1 : Number(element.shangpianyield);
      const dumoYield = Number(element.dumoyield) === 0 ? 1 : Number(element.dumoyield);
      const dianjiaoYield = Number(element.dianjiaoyield) === 0 ? 1 : Number(element.dianjiaoyield);
      const weitiaoYield = Number(element.weitiaoyield) === 0 ? 1 : Number(element.weitiaoyield);
      const fenghanYield = Number(element.fenghanyield) === 0 ? 1 : Number(element.fenghanyield);
      const ceshiYield = Number(element.ceshiyield) === 0 ? 1 : Number(element.ceshiyield);
      // eslint-disable-next-line no-param-reassign
      element.fpy = (shangpianYield * dumoYield * dianjiaoYield * weitiaoYield * fenghanYield * ceshiYield).toFixed(
        2
      ) as string;
    });
    fpyOptions.data = rawData;
    buildChartSelect(rawData);
    buildChart(fpyOptions.data as any);
  }
};

const getAreaList = async () => {
  const result = await fetchAreaList();
  if (result.data) {
    areas.value = result.data;
  }
};

onMounted(async () => {
  getAreaList();
});
</script>
<style scoped></style>
